package main

import (
	"flag"
	"fmt"
	"net/http"

	"user/internal/config"
	"user/internal/handler"
	"user/internal/handler/common"
	middlewars "user/internal/middlewares"
	"user/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

var configFile = flag.String("f", "etc/user-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	// 2. 跨域问题
	// - 简单(不可掉位置)
	// rest.WithCors("http://localhost:8080")
	// rest.WithCorsHeaders("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	// - 自定义
	rest.WithCustomCors(common.CorsHandler(), func(w http.ResponseWriter) {
		// no setting
	})
	// 3. 自定义中间件(认证, 限流等)
	server.Use(middlewars.DemoMiddleware())

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 1.统一错误管理
	httpx.SetErrorHandler(common.ErrorHandler)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
